// pages/collect/collect.js
Page({
    data: {
      collections: [],            // 收藏的商品列表
      page: 1,                    // 当前页码
      pageSize: 10,               // 每页数量
      total: 0,                   // 总数量
      loading: false,             // 加载中状态
      noMoreCollections: false,   // 没有更多商品
      userInfo: null              // 用户信息
    },
  
    onLoad() {
      this.checkUserInfo();
      this.loadMyCollections();
    },
  
    onShow() {
      // 页面显示时重新加载收藏的商品，确保数据最新
      this.loadMyCollections(true);
    },
  
    onPullDownRefresh() {
      // 下拉刷新
      this.loadMyCollections(true);
      wx.stopPullDownRefresh();
    },
  
    onReachBottom() {
      // 触底加载更多
      if (!this.data.loading && !this.data.noMoreCollections) {
        this.loadMyCollections();
      }
    },
  
    // 检查用户信息
    checkUserInfo() {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({ userInfo });
      } else {
        wx.navigateTo({ url: '/pages/login/index' });
      }
    },
  
    // 加载我收藏的商品
    loadMyCollections(refresh = false) {
      if (refresh) {
        this.setData({
          page: 1,
          collections: [],
          noMoreCollections: false
        });
      }
  
      if (this.data.loading || this.data.noMoreCollections) return;
  
      this.setData({ loading: true });
  
      wx.cloud.callFunction({
        name: 'getMyCollections',
        data: {
          userId: this.data.userInfo._id,
          page: this.data.page,
          pageSize: this.data.pageSize
        },
        success: res => {
          this.setData({ loading: false });
          console.log(res);
          if (res.result && res.result.success) {
            const newCollections = res.result.data.list;
            const total = res.result.data.total;
            newCollections.forEach(item=>{
                if(item.goodsInfo.goodsImage){
                    let arr = item.goodsInfo.goodsImage.split(',')
                    item.goodsImage=arr
                }
            })
            this.setData({
              collections: refresh ? newCollections : [...this.data.collections, ...newCollections],
              page: this.data.page + 1,
              total: total
            });
            
            // 判断是否还有更多商品
            this.setData({
              noMoreCollections: this.data.collections.length >= total
            });
          } else {
            wx.showToast({
              title: res.result.message || '加载收藏失败',
              icon: 'none'
            });
          }
        },
        fail: err => {
          this.setData({ loading: false });
          console.error('加载我收藏的商品失败', err);
          wx.showToast({
            title: '加载失败',
            icon: 'none'
          });
        }
      });
    },
  
    // 前往商品详情页
    goToGoodsDetail(e) {
      const goodsId = e.currentTarget.dataset.goodsId;
      wx.navigateTo({
        url: `/pages/goods/index?goodsId=${goodsId}`
      });
    },
  
    // 取消收藏
    cancelCollection(e) {
        console.log(e);
      const collectionId = e.currentTarget.dataset.collectionId;
      const collection = this.data.collections.find(item => item._id === collectionId);
      console.log(collection);
      wx.showModal({
        title: '提示',
        content: '确定要取消收藏吗？',
        success: async (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '处理中...' });
            
            try {
              await wx.cloud.callFunction({
                name: 'cancelCollection',
                data: {
                  collectionId: collectionId,
                  goodsId: collection.goodsId
                }
              });
              
              // 重新加载收藏的商品
              this.loadMyCollections(true);
              wx.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } catch (error) {
              console.error('取消收藏失败', error);
              wx.showToast({
                title: '取消失败',
                icon: 'none'
              });
            } finally {
              wx.hideLoading();
            }
          }
        }
      });
    }
  });